package com.levy.process.exec;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created with IntelliJ IDEA. User: jason Date: 7/23/13 Time: 2:27 PM To change
 * this template use File | Settings | File Templates.
 */
public class ProcessUtils {

	public static void runSH(String processKeyWords) {
		try {
			String[] cmd = {
                    "/bin/sh",
                    "-c",
                    "ps aux | grep \""+processKeyWords+"\" | grep -v grep > /dev/null"};
			print(cmd);
			Process process = Runtime.getRuntime().exec(cmd);
			BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); 		 
			String str;
			while((str=br.readLine())!=null){ 
				System.out.println("***"+str); 
			} 
			
			int resultCode = process.waitFor();
			if (resultCode == 0){
				System.out.println("Run sh successful with retrun code: " + resultCode); 
			}else{
				System.out.println("Run sh failed with retrun code: " + resultCode); 
			}

		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}	

	public static void runJar() {
		try {
			String[] cmd = { "java", "-cp", "/home/levy.xia/workspace/LevyProject/src/main/java", "com.levy.process.exec.ProcessRun" };
			print(cmd);
			Process process = Runtime.getRuntime().exec(cmd);
			int resultCode = process.waitFor();
			if (resultCode == 0){
				System.out.println("Run java successful with retrun code: " + resultCode); 
			}else{
				System.out.println("Run java failed with retrun code: " + resultCode); 
			}
			

		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public static void runPython() {
		try {
			String[] cmd = { "python", "..." };
			print(cmd);
			Process process = Runtime.getRuntime().exec(cmd);
			int resultCode = process.waitFor();
			if (resultCode == 0){
				System.out.println("Run python successful with retrun code: " + resultCode); 
			}else{
				System.out.println("Run python failed with retrun code: " + resultCode); 
			}
			

		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public static void print(String[] cmd) {
		StringBuffer buf = new StringBuffer();
		for (String s : cmd) {
			buf.append(s);
			buf.append(" ");
		}
		System.out.println("Run:  " + buf);
	}
	
	public static void main(String[] args) {
		runSH("java");
		runJar();
	}
	
}
